/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 *
 * @author Thomas
 */
public class BrowseFiles extends javax.swing.JFrame {

    private String path = System.getProperty("user.dir")+"\\";
    private DefaultListModel listModel;
    private File directory;
    private File files;
    private BufferedImage image;
    private Graphics drawImage;
    /**
     * Creates new form BrowseFiles
     */
    public BrowseFiles() {
        initComponents();
        showFolders();
        fileText.setVisible(false);
        fileTextPanel.setVisible(false);
    }
    
    private void showFolders()
    {
        listModel = new DefaultListModel();
        directory = new File(this.path);
        String[] children = directory.list();
        for (int i=0; i<children.length; i++) {
            listModel.addElement(children[i]);
        }
        folderList.setModel(listModel);
    }
    
    private void showFiles(String folder)
    {
        listModel = new DefaultListModel();
        files = new File(this.path+folder+"\\");
        String[] children = files.list();
        for (int i=0; i<children.length; i++) {
            listModel.addElement(children[i]);
        }
        fileList.setModel(listModel);
    }
    private void previewFile(String file) throws IOException {
        ImageScaler scaleImage = new ImageScaler();
        if(file.contains(".dat"))
        {
            fileTextPanel.setLocation(0, 250);
            fileText.setLocation(graphPreview.getLocation());
                    
            graphPreview.setVisible(false);
            fileTextPanel.setVisible(true);
            fileText.setVisible(true);
            BufferedReader br = new BufferedReader(new FileReader(new File(this.path+file)));

            String s = null;
            String tmp = null;
            while((s = br.readLine()) != null){
                tmp += s+"\n\r";
            }
            br.close();
            fileText.setText(tmp);
           }
        else
        {
            fileTextPanel.setVisible(false);
            fileText.setVisible(false);
            graphPreview.setVisible(true);
            image = ImageIO.read(new File(this.path+file));
            graphPreview.setIcon(scaleImage.getImage(250, 250, image));
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        browseText = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        folderList = new javax.swing.JList();
        showFileButton = new javax.swing.JButton();
        deleteFileButton = new javax.swing.JButton();
        foldersTextLabel = new javax.swing.JLabel();
        filesTextLabel = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        fileList = new javax.swing.JList();
        changeFolderButton = new javax.swing.JButton();
        defaultPathButton = new javax.swing.JButton();
        infoPanel = new javax.swing.JPanel();
        fileTextPanel = new javax.swing.JScrollPane();
        fileText = new javax.swing.JTextArea();
        graphPreview = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        browseText.setFont(new java.awt.Font("Tahoma", 1, 14));
        browseText.setText("Browse previously generated graphs here");

        folderList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                folderListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(folderList);

        showFileButton.setText("Show file");
        showFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showFileButtonActionPerformed(evt);
            }
        });

        deleteFileButton.setText("Delete file");
        deleteFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteFileButtonActionPerformed(evt);
            }
        });

        foldersTextLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        foldersTextLabel.setText("Folders");

        filesTextLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        filesTextLabel.setText("Files");

        fileList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(fileList);

        changeFolderButton.setText("Change Path");
        changeFolderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeFolderButtonActionPerformed(evt);
            }
        });

        defaultPathButton.setText("Reset default path");
        defaultPathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                defaultPathButtonActionPerformed(evt);
            }
        });

        fileText.setColumns(20);
        fileText.setLineWrap(true);
        fileText.setRows(5);
        fileText.setEnabled(false);
        fileTextPanel.setViewportView(fileText);

        javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
        infoPanel.setLayout(infoPanelLayout);
        infoPanelLayout.setHorizontalGroup(
            infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 243, Short.MAX_VALUE)
            .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infoPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(graphPreview, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
            .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infoPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(fileTextPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(13, Short.MAX_VALUE)))
        );
        infoPanelLayout.setVerticalGroup(
            infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 170, Short.MAX_VALUE)
            .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infoPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(graphPreview, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
            .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infoPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(fileTextPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 676, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(browseText)
                            .addGap(0, 368, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
                                .addComponent(foldersTextLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(changeFolderButton, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
                                    .addGap(18, 18, 18)
                                    .addComponent(defaultPathButton)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(filesTextLabel)
                                        .addComponent(showFileButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(deleteFileButton))
                                    .addGap(0, 322, Short.MAX_VALUE)))))
                    .addContainerGap()))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 419, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(browseText)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(foldersTextLabel)
                        .addComponent(filesTextLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(changeFolderButton)
                                .addComponent(defaultPathButton))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGap(0, 105, Short.MAX_VALUE)
                            .addComponent(deleteFileButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(showFileButton)
                            .addGap(13, 13, 13)))
                    .addContainerGap()))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(95, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void folderListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_folderListMouseClicked
        // TODO add your handling code here:
        String folder = (String)folderList.getSelectedValue();
        showFiles(folder);
    }//GEN-LAST:event_folderListMouseClicked

    private void fileListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileListMouseClicked
        // TODO add your handling code here:
        String folder = (String)folderList.getSelectedValue()+"\\";
        String file = (String)fileList.getSelectedValue();
        String fullPath = folder+file;
        try {
            previewFile(fullPath);
        } catch (IOException ex) {
            Logger.getLogger(BrowseFiles.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_fileListMouseClicked

    private void changeFolderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeFolderButtonActionPerformed
        // TODO add your handling code here:
        int n = JOptionPane.showConfirmDialog(null,"Are you sure you want to change path?","Warning! Really change path?",JOptionPane.YES_NO_OPTION);

        if(n==0)
        {
            String newFolder = "";
            JFileChooser fileChoose = new JFileChooser();
            fileChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChoose.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
                newFolder =  fileChoose.getSelectedFile().toString();
            }
            System.out.println(this.path);
            System.out.println(newFolder);
            this.path = newFolder+"\\";
            showFolders();
        }
    }//GEN-LAST:event_changeFolderButtonActionPerformed

    private void defaultPathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultPathButtonActionPerformed
        // TODO add your handling code here:
        this.path = System.getProperty("user.dir")+"\\";
        showFolders();
    }//GEN-LAST:event_defaultPathButtonActionPerformed

    private void showFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showFileButtonActionPerformed
        // TODO add your handling code here:
        String folder = (String)folderList.getSelectedValue()+"\\";
        String file = (String)fileList.getSelectedValue();
        String fullPath = folder+file;
        if(fullPath.contains(".dat"))
        {
            try{
            JTextArea displayFile = new JTextArea(20, 60);  
            displayFile.read(new FileReader(this.path+fullPath), null);  
            displayFile.setEditable(false);  
            JOptionPane.showMessageDialog(null, new JScrollPane(displayFile)); 
            }
            catch(IOException ioe) {
            }  
        }
        else{
            final ImageIcon image = new ImageIcon(this.path+fullPath);
            JOptionPane.showMessageDialog(null, image, "Graph", JOptionPane.INFORMATION_MESSAGE, null);
        }
    }//GEN-LAST:event_showFileButtonActionPerformed

    private void deleteFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteFileButtonActionPerformed
        // TODO add your handling code here:
        String folder = (String)folderList.getSelectedValue()+"\\";
        String file = (String)fileList.getSelectedValue();
        String fullPath = folder+file;
        int n = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete the selected file?","Delete File?",JOptionPane.YES_NO_OPTION);
        if(n==0)
        {
            File delFile = new File(this.path+fullPath);
            delFile.delete();
            showFiles(folder);
        }
    }//GEN-LAST:event_deleteFileButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BrowseFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BrowseFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BrowseFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BrowseFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BrowseFiles().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel browseText;
    private javax.swing.JButton changeFolderButton;
    private javax.swing.JButton defaultPathButton;
    private javax.swing.JButton deleteFileButton;
    private javax.swing.JList fileList;
    private javax.swing.JTextArea fileText;
    private javax.swing.JScrollPane fileTextPanel;
    private javax.swing.JLabel filesTextLabel;
    private javax.swing.JList folderList;
    private javax.swing.JLabel foldersTextLabel;
    private javax.swing.JLabel graphPreview;
    private javax.swing.JPanel infoPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton showFileButton;
    // End of variables declaration//GEN-END:variables

}
